<?php
$campusapp_redirecturl="https://wx.ccom.edu.cn/wap/proxy";
$campusapp_source="library";
$campusapp_key="i3pwYW8asEhr";
$campusapp_host='https://wx.ccom.edu.cn';

$campusapp_url="https://eaiapp.ccom.edu.cn";
$campusapp_appid="200200405134542698";
$campusapp_appsecret="smeyasjgy1tksxm9bmpv5gnhjbaf6ngu";

$yzf_url="https://yzf.qq.com/xv/web/static/chat/index.html";
$yzf_sign="37ef9b97d62350c02246cdeb19b2b165670e5495c9741c40c09ae2a4c418646c957e888e4d10cf0df64f7f1eec00d7eaa59291";

/* Internal function used in campusapp */
function campusapp_formatBizQueryParamMap($paramMap, $urlencode = false)
{
        $buff = "";
        foreach ($paramMap as $k => $v)
        {
                if ($v === "" || $v === null) continue;
                if($urlencode)
                {
                   $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0)
        {
                $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
}

function campusapp_getSign($Parameters, $key='')
{
        ksort($Parameters);
        $String = campusapp_formatBizQueryParamMap($Parameters, false);
        $String = $String."&key=".$key;
        $String = md5($String);
        $result = strtoupper($String);
        return $result;
}

header("Cache-Control: public");
header("Pragma: cache");

if($_SERVER['REQUEST_METHOD']=='POST') {
	$result=new stdClass();
	$result->e='9999';
	$result->m='About to redirect.';
	header('Content-type: application/json');
	echo json_encode($result);
	exit;
}

if(preg_match('/MicroMessenger\//', $_SERVER['HTTP_USER_AGENT'])) {
	if(!array_key_exists('code', $_GET)) $should_redirect=1;
	else {
		$url=sprintf("%s/api/third/get-token", $campusapp_url);
		$opts=['appid'=>$campusapp_appid, 'appsecret'=>$campusapp_appsecret];
		$ch = curl_init($url.'?'.http_build_query($opts));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$r=curl_exec($ch);
		$result=json_decode($r);
		if($r===FALSE || $result->e || empty($result->d->access_token)) {
			http_response_code(500); exit;
		}
		curl_close($ch);

		$url=sprintf("%s/uc/api/oauth/user-by-code", $campusapp_url);
		$opts=['code'=>$_GET['code'], 'access_token'=>$result->d->access_token];
		$ch = curl_init($url.'?'.http_build_query($opts));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$r=curl_exec($ch);
		$result=json_decode($r);
		if($r===FALSE || $result->e || empty($result->d->role->number)) {
			$should_redirect=1;
		} else {
			curl_close($ch);
			$uid=$result->d->role->number;
		}
	}

	if($should_redirect==1) {
		$url=sprintf('Location: %s/uc/api/oauth/index?redirect=%s&appid=%s',
			$campusapp_url,
			urlencode(sprintf('%s://%s%s',$_SERVER['HTTPS']?'https':'http',$_SERVER['HTTP_HOST'],$_SERVER['REQUEST_URI'])),
			$campusapp_appid
		);
        	header($url, TRUE, 302);
	        exit;
	} else {
		$url=sprintf('Location: %s?sign=%s&uid=%s', $yzf_url, $yzf_sign, $uid);
		header($url, TRUE, 302);
		exit;
	}
}

?>
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
    <title>云智服登录页</title>
    <link rel="stylesheet" href="./impower.css">
    <script src="//cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="//cdn.bootcss.com/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js"></script>
    <script type="text/javascript" src="<?php echo $campusapp_host;?>/js/mxqrcode.js"></script>
    <script type="text/javascript" src="<?php echo $campusapp_host;?>/js/mxsocket.js"></script>
    <style>
#qrcode > img {
    width: 280px;
    height: 280px;
    margin-top: 15px;
    border: 1px solid #E2E2E2;
}
    </style>
<script type="text/javascript">
function drawQrCode (qrcodePlaceholder="#qrcode") {
	var q=new mxqrcode({
            debug: true,// 需要修改，是否开启debug
            host: "<?php echo $campusapp_host;?>",// 需要更改为真实的萌校域名
            channel: "normal",// 默认使用normal
            success: function(msg)//用户操作后所调用的函数
            {
                console.log(msg);
		if(msg.e=="9999") {
			var url="<?php echo $yzf_url; ?>?sign=<?php echo $yzf_sign?>&uid="+msg.data.xgh;
			top.window.location.href=url;
		} else {
			location.reload();
		}
            },
            error: function(msg)//服务器发生异常时所调用的函数
            {
                console.log(msg);
            },
            ext: {
                "apiUrl":"<?php printf('%s://%s%s',$_SERVER['HTTPS']?'https':'http',$_SERVER['HTTP_HOST'],$_SERVER['REQUEST_URI']);?>",
                "apiKey":"<?php echo $campusapp_source; ?>"
            },//业务所需要的参数
            div: qrcodePlaceholder,
            title: "登录图书馆客服系统",
            scanfinish: function(msg)// 用户扫描二维码后所调用的函数
            {
                console.log(msg);
		$("#wx_default_tip").hide();
		$("#wx_after_scan").show();
            }
        });
	setTimeout(drawQrCode, 1000*60, "#qrcodePlaceholder");

        if(qrcodePlaceholder!="#qrcode") {
                $(qrcodePlaceholder).imagesLoaded(function () {
                        $("#qrcode > img").first().attr("src", q.opts.host + "/api/mx-socket/qrcode"+"?ticket=" + q.opts.ticket + "&channel=" + q.opts.channel);
                });
        }

}

$(function(){
	drawQrCode("#qrcode");
});
</script>
</head>
<body style="background-color: rgb(51, 51, 51); padding: 50px;">
		<div class="old-template" style="">
			<div class="main impowerBox">
				<div class="loginPanel normalPanel">
					<div class="title">微信登录</div>
					<div class="waiting panelContent">
						<div class="wrp_code" id="qrcode"></div>
						<div class="wrp_code" id="qrcodePlaceholder" style="display: none"></div>
						<div class="info">
							<div class="status status_browser js_status js_wx_default_tip normal" id="wx_default_tip"><p>请使用微信扫描二维码登录</p><p>“中央音乐学院图书馆客服系统”</p></div>
							<div class="status status_succ js_status js_wx_after_scan normal" style="display: none;" id="wx_after_scan"><i class="status_icon icon38_msg succ"></i><div class="status_txt"><h4>扫描成功</h4><p>请在微信中点击确认即可登录</p></div></div>
				        </div>
					</div>
				</div>
			</div>
		</div>
</body>
</html>
